/*
 * Venus.cpp
 *
 *  Created on: Nov 20, 2011
 *      Author: ECE_Guest
 */


#define START1 0xA0
#define START2 0xA1
#define END1 0x0D
#define END2 0x0A

#define MAX_PKTLEN 64

static uint8_t pkt[MAX_PKTLEN+1];

// OUTPUT MESSAGE FORMATS
// 0x02 - ACK
#define MO_ACK 0x02
typedef struct {
 uint8_t message_type; // the message being ACKd
} mo_ack_t;

// 0x03 - NACK
#define MO_NACK 0x03
typedef struct {
 uint8_t message_type; // the message being NACKd
} mo_nack_t;

// 0x04 - position update
#define MO_POSHZ 0x04
typedef struct {
 uint8_t rate; // see M_POSHZ
} mo_poshz_t;

// 0x05 - navigation data
#define MO_NAVDATA 0x05
typedef struct {
 uint8_t fixmode; // 0 = none; 1 = 2D, 2 = 3D; 3 = 3D+DGPS
 uint8_t svnum; // number of sats in fix
 uint16_t gps_week; // GPS Week Number
 uint32_t gps_tow; // Time of week, seconds, 1/100th resolution
 int32_t lattitde; // 1/1e-7 (???) degree, positive north
 int32_t longitude; // 1/1e-7 (???) degree, positive east
 uint32_t elips_alt; // meters, 1/100th
 uint32_t sea_alt; // meters, 1/100th
 uint16_t gdop; // 1/100th
 uint16_t pdop; // 1/100th
 uint16_t hdop; // 1/100th
 uint16_t vdop; // 1/100th
 uint16_t tdop; // 1/100th
 int32_t ecef_x; // meters, 1/100th
 int32_t ecef_y; // meters, 1/100th
 int32_t ecef_z; // meters, 1/100th
 int32_t ecef_vx; // meters, 1/100th
 int32_t ecef_vy; // meters, 1/100th
 int32_t ecef_vz; // meters, 1/100th
} mo_navdata_t;

// END BINARY MESSAGES





uint8_t venus634_crc(uint8_t type, void *payload, uint16_t len) {
 uint8_t crc = 0, n;

 // message type first
 crc ^= type;

 // and then the payload
 for (n = 0; n < len; n++) {
  crc ^= *((uint8_t *)payload);
  payload++;
 }
 return crc;
}

void venus634_send(uint8_t type, void *payload, uint16_t len, void (*ptWrite)(uint8_t)) {
 uint8_t crc, n, rc = 0xff, intype;
 uint16_t inlen;

 // first compute the CRC of the given message
 crc = venus634_crc(type, payload, len);

 // now send the message
 // header
 ptWrite(START1);
 ptWrite(START2);
 ptWrite(len & 0xff);
 ptWrite(len >> 8);
 // type and payload
 ptWrite(type);
 for (n = 0; n < len; n++) {
  ptWrite(*(uint8_t *)payload);
  payload++;
 }
 // checksum and tail
 ptWrite(crc);
 ptWrite(END1);
 ptWrite(END2);

 // done!
 return;
}





